var mapApp = new Object();

var layer1 = new ol.layer.Tile({
    source: new ol.source.XYZ({
        // origin: [-180, 90],
        // transparent: true,
        url: "http://t2.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=008a8816d2eee25a677670273eaee891",
        crossOrigin: "anonymous"
    }),
    projection: 'EPSG:4326'
});
layer1.set("title", "layer1")
var layer2 = new ol.layer.Tile({
    source: new ol.source.XYZ({
        // origin: [-180, 90],
        // transparent: true,
        url: "http://t2.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=008a8816d2eee25a677670273eaee891",
        crossOrigin: "anonymous"
    }),
    projection: 'EPSG:4326'
});
layer2.set("title", "layer2")
var View = new ol.View({
    center: [120.18, 35.97],
    zoom: 9,
    projection: 'EPSG:4326',
});
var map = new ol.Map({
    target: 'map',
    controls: ol.control.defaults({attributionOptions: {collapsed: false}})
        .extend([new ol.supermap.control.Logo()]),
    view: View,
    layers: [layer1, layer2]
});
map.set("title", "mapApp.olMap")
mapApp.olMap = map;

function openFp(state){
    if(state){
        var layers = mapApp.olMap.getLayers().getArray();
        document.getElementById('map').innerHTML='';
        document.getElementById("map").style.width = "50%" ;
        document.getElementById("map").style.float = "left" ;
        document.getElementById("map1").style.display = "inline" ;
        var map = new ol.Map({
            target: 'map',
            controls: ol.control.defaults({attributionOptions: {collapsed: false}})
                .extend([new ol.supermap.control.Logo()]),
            view: View
        });
        map.set("title", "mapApp.olMap")
        mapApp.olMap = map;
        for (var i = 0; i < layers.length; i++) {
            mapApp.olMap.addLayer(layers[i])
        }
        mapApp.olMap.fenpingF = new ol.Map({
            target: 'map1',
            controls: ol.control.defaults({attributionOptions: {collapsed: false}})
                .extend([new ol.supermap.control.Logo()]),
            view: View,
            layers:[layer1,layer2]
        });
        mapApp.olMap.fenpingF.set("title","mapApp.olMap.fenpingF")
    }else{
        var layers = mapApp.olMap.getLayers().getArray();
        document.getElementById('map1').innerHTML='';
        document.getElementById('map').innerHTML='';
        document.getElementById("map").style.width = "100%" ;
        document.getElementById("map").style.clear = "both" ;
        document.getElementById("map1").style.display = "none" ;
        var map = new ol.Map({
            target: 'map',
            controls: ol.control.defaults({attributionOptions: {collapsed: false}})
                .extend([new ol.supermap.control.Logo()]),
            view: View
        });
        map.set("title", "mapApp.olMap")
        mapApp.olMap = map;
        for (var i = 0; i < layers.length; i++) {
            mapApp.olMap.addLayer(layers[i])
        }

    }
}

//图层叠加
function QieHuanTuCeng(direction, id, url, state) {
    if (direction == "left") {
        if (state) {
            if (url.length==4) {
                return;
            } else {
                var tempLayer = new ol.layer.Tile({
                    source: new ol.source.TileSuperMapRest({
                        url: "http://" + url,
                        origin: [-180, 90],
                        transparent: true,
                        tileLoadFunction: function (imageTile, src) {
                            imageTile.getImage().crossOrigin = 'anonymous';
                            imageTile.getImage().src = src;
                        }
                    }),
                    projection: 'EPSG:4326'
                });
                tempLayer.set("title", id)
                mapApp.olMap.addLayer(tempLayer)

            }
        } else {
            removLayer(mapApp.olMap, id);
        }
    } else {
        if (state) {
            if (url.length==4) {
                return;
            } else {
                var tempLayer = new ol.layer.Tile({
                    source: new ol.source.TileSuperMapRest({
                        url: "http://" + url,
                        origin: [-180, 90],
                        transparent: true,
                        tileLoadFunction: function (imageTile, src) {
                            imageTile.getImage().crossOrigin = 'anonymous';
                            imageTile.getImage().src = src;
                        }
                    }),
                    projection: 'EPSG:4326'
                });
                tempLayer.set("title", id)
                mapApp.olMap.fenpingF.addLayer(tempLayer)
            }
        } else {
            removLayer(mapApp.olMap.fenpingF, id);
        }
    }
}

function removLayer(map2, layerName) {
    var layers = map2.getLayers().getArray();
    for (var i = 0; i < layers.length; i++) {
        if (layers[i].getProperties().title == layerName) {
            map2.removeLayer(layers[i]);
            break;
        }
    }
}


/**
 * 透明度
 * state：true启用，false关闭
 */
function TouMingDu(state,value) {
    var layers = mapApp.olMap.getLayers().getArray();
    if (state) {
        for (var i = layers.length - 1; i > 0; i--) {
            layers[i].setOpacity(value);
        }
    }
}



/**
 * 坐标定位
 * state：true启用，false关闭
 */
function ZuoBiaoDingWei(lon,lat) {
    var View = mapApp.olMap.getView();
    if (lon && lat) {
        View.setCenter([parseFloat(lon), parseFloat(lat)]);
        View.setZoom(14);
        //创建图标特性
        var iconFeature = new ol.Feature({
            geometry: new ol.geom.Point([lon, lat]),
            name: "my Icon"
        });
        //创建空的矢量容器
        var source = new ol.source.Vector({wrapX: false});
        //将图标特性添加进矢量中
        source.addFeature(iconFeature);
        //创建图标样式
        var iconStyle = new ol.style.Style({
            image: new ol.style.Icon({
                opacity: 1,
                src: "../assets/images/marker-icon.png"
            })
        });
        //创建图标层
        var zuobiaodingweiLayer = new ol.layer.Vector({
            source: source,
            style: iconStyle,
            title: "zuobiaodingwei"
        });
        mapApp.olMap.addLayer(zuobiaodingweiLayer);
    } else {
        removLayer(mapApp.olMap, "zuobiaodingwei");
    }
}

/**
 *
 * 全图
 */
var View=mapApp.olMap.getView();
var zoom = View.getZoom();
var center = View.getCenter();
var zoom = View.getZoom();
function quantu(){
    View.setZoom(zoom);
    View.setCenter( center);
}




/**
 *清空图层
 *direction代表着哪个图层
 *left左图层
 * right右图层
 */
function QingKongTuCeng(state) {
    if(state == "left"){
        if (mapApp.olMap.getLayers()) {
            var layers = mapApp.olMap.getLayers().getArray();
            for(var i=0;i< layers.length;i++){
                if(layers[i].getProperties().title!="layer1"&&layers[i].getProperties().title!="layer2"){
                    mapApp.olMap.removeLayer(layers[i]);
                    i--;
                }
            }
        }
    }else{
        if (mapApp.olMap.fenpingF) {
            var layers = mapApp.olMap.fenpingF.getLayers().getArray();
            for(var i=0;i< layers.length;i++){
                if(layers[i].getProperties().title!="layer1"&&layers[i].getProperties().title!="layer2"){
                    mapApp.olMap.fenpingF.removeLayer(layers[i]);
                    i--;
                }
            }
        }
    }

}

function addImageLayer(state){
    if(state){
        var imageLayer = new ol.layer.Tile({
            source: new ol.source.XYZ({
                crossOrigin: "anonymous",
                url: "http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=008a8816d2eee25a677670273eaee891"
            }),
            projection: 'EPSG:4326'
        });
        mapApp.olMap.addLayer(imageLayer);
    }else{
        var layer1 = new ol.layer.Tile({
            source: new ol.source.XYZ({
                // origin: [-180, 90],
                // transparent: true,
                crossOrigin: "anonymous",
                url: "http://t2.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=008a8816d2eee25a677670273eaee891"
            }),
            projection: 'EPSG:4326'
        });

        var layer2 = new ol.layer.Tile({
            source: new ol.source.XYZ({
                // origin: [-180, 90],
                // transparent: true,
                // crossOrigin: "anonymous",
                url:  "http://t2.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=008a8816d2eee25a677670273eaee891"
            }),
            projection: 'EPSG:4326'
        });
        mapApp.olMap.addLayer(layer1);
        mapApp.olMap.addLayer(layer2);
    }
}


/* 规划选址弹出层 */
var ghxzIdx;
var openghxzFun = function(ghxzdata){
    $("#selectSiteTable").html("");
    $("input[name='proName']").val(ghxzdata.result.proName);
    $("input[name='unit']").val(ghxzdata.result.unit);
    $("input[name='type']").val(ghxzdata.result.type);

    var listData = ghxzdata.result.siteList;
    if (listData.length > 0) {
        getXZFXresult(ghxzdata);
        var len = listData.length;
        if (len > 5) {
            len = 5;
        }
        var checktf = "";
        var numList = ['A','B','C','D','E'];
        for (var i=0;i<len;i++) {
            $("#selectSiteTable").append(
                '<tr>'
                +'    <td><span class="select-site alert-checkbox" data-val="'+listData[i].smId+'"></span></td>'
                +'    <td>地块'+numList[i]+'</td>'
                +'    <td>'+listData[i].area+'</td>'
                +'    <td>'+listData[i].dlmj+'</td>'
                +'    <td>'+listData[i].rk+'</td>'
                +'    <td>'+listData[i].point+'</td>'
                +'</tr>'
            );
        }
    } else {
        $("#selectSiteTable").append(
            '<tr>'
            +'    <td colspan="6">没有符合的地块</td>'
            +'</tr>'
        );
    }

    $('#selectSite').show();
};

var closeghxzFun = function () {
    $('#selectSite').hide();
};

var identity = sessionStorage.identity;
var getWebRootPath = function () {
    var curWwwPath = window.top.location.host;
    var localhostPath = "http://" + curWwwPath;
    return (localhostPath);
};

/* 提交选址意见 */
$("#selectSiteBtn").click(function () {
    var tf = $(".alert-checked").length;
    if (tf == 0) {
        window.top.publicFun.msgFun('请选择地块！');
        return false;
    }
    var yj = $("#xzyj").val();
    if (yj == '') {
        window.top.publicFun.msgFun('请填写选址意见！');
        return false;
    }

    var smid = $(".alert-checked").attr("data-val");
    $.ajax({
        type: "PUT",
        url: getWebRootPath() + "/api/siteselection",
        dataType: "json",

        data: JSON.stringify({
            smId: ''+smid,//地块ID
            proName: $("input[name='proName']").val(),//项目名称
            unit: $("input[name='unit']").val(),//施工单位
            type: $("input[name='type']").val(),//分类 1商业 2工业 3居住
            opinion: yj,//选址意见
            x: $("input[name='xstr']").val(),//x
            y: $("input[name='ystr']").val()//y
        }),
        beforeSend: function (xhr) {
            xhr.setRequestHeader("x-auth-token", identity);
        },
        success: function (data, status, xhr) {
            if (data.success) {
                window.top.publicFun.msgFun("选址成功！");
                guiHuaXuanzhi(false);
                $('#selectSite').hide();
            } else {
                window.top.publicFun.msgFun(data.error);
                return false;
            }
        },
        error: function (err) {
            if (err.status == "401") {
                window.top.location.replace("../login.html");
            } else {
                window.top.publicFun.msgFun("选址失败！");
            }
            return false;
        }
    });
});

/* 选择地块单选 */
$(document).on('click','.select-site',function () {
    if (!$(this).hasClass("alert-checked")) {
        var lastobj = $(".alert-checked");
        if (lastobj.length > 0) {
            zoomToPolygon(lastobj.attr("data-val"),false);
        }

        $('.select-site').removeClass("alert-checked");
        $(this).addClass("alert-checked");

        /**
         * 地图显示选址分析多边形
         *id:多边形id
         * state：打开关闭状态
         */
        var id = $(this).attr("data-val");
        zoomToPolygon(id,true);
        var xystr = polygonCenter(id);
        var xyList = xystr.split(",");
        $("input[name='xstr']").val(xyList[0]);
        $("input[name='ystr']").val(xyList[1]);
    }
});


/**
 * 截屏
 * state：true启用，false关闭
 */

function mapJiePing(state) {
    if (state) {
        mapApp.olMap.once('postcompose', function (event) {
            var canvas = event.context.canvas;
            canvas.toBlob(function (blob) {
                saveAs(blob, 'map.png');
            });
        });
        mapApp.olMap.renderSync();
    }
}


var sketch;
var helpLineTooltipElement;
var helpPolygonTooltipElement;
var helpLineTooltip;
var helpPolygonTooltip;
var measureLineTooltipElement;
var measurePolygonTooltipElement;
var measureLineTooltip;
var measurePolygonTooltip;
var draw;

function formatLength(line) {
    var wgs84Sphere = new ol.Sphere(6378137);
    var coordinates = line.getCoordinates();
    var length = 0;
    for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {
        length += wgs84Sphere.haversineDistance(coordinates[i], coordinates[i + 1]);
    }
    var output;
    if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) +
            ' ' + 'km';
    } else {
        output = (Math.round(length * 100) / 100) +
            ' ' + 'm';
    }
    return output;
}

function formatArea(polygon) {
    var wgs84Sphere = new ol.Sphere(6378137);
    var coordinates = polygon.getLinearRing(0).getCoordinates();
    var area = Math.abs(wgs84Sphere.geodesicArea(coordinates));
    var output;
    if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) +
            ' ' + 'km<sup>2</sup>';
    } else {
        output = (Math.round(area * 100) / 100) +
            ' ' + 'm<sup>2</sup>';
    }
    return output;
}

function addInteraction(parm) {
    var type = (parm === 'mian' ? 'Polygon' : 'LineString');
    console.log(type)
    console.log(type === "LineString")
    if (type === "LineString") {
        var source = new ol.source.Vector({wrapX: false});
        lineLayer = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: "rgba(255,255,255,0.5)"
                }),
                stroke: new ol.style.Stroke({
                    color: "blue"
                })
            }),
            title: "line",
            zIndex: 10000
        });
        mapApp.olMap.addLayer(lineLayer);
        draw = new ol.interaction.Draw({
            source: source,
            type: type,
            title: "drawLine"
        });
        mapApp.olMap.addInteraction(draw);
        createLineMeasureTooltip();
        createLineHelpTooltip();

        var listener;
        draw.on('drawstart',
            function (evt) {
                // set sketch
                sketch = evt.feature;
                /** @type {module:ol/coordinate~Coordinate|undefined} */
                var tooltipCoord = evt.coordinate;
                listener = sketch.getGeometry().on('change', function (evt) {
                    var geom = evt.target;
                    var output;
                    output = formatLength(geom);
                    tooltipCoord = geom.getLastCoordinate();

                    measureLineTooltipElement.innerHTML = output;
                    measureLineTooltip.setPosition(tooltipCoord);
                });
            }, this);

        draw.on('drawend',
            function () {
                measureLineTooltipElement.className = 'tooltip tooltip-static';
                measureLineTooltip.setOffset([0, -7]);
                // unset sketch
                sketch = null;
                // unset tooltip so that a new one can be created
                measureLineTooltipElement = null;
                createLineMeasureTooltip();
                new ol.Observable(listener);
            }, this);
    } else if (type == "Polygon") {
        var source = new ol.source.Vector({wrapX: false});
        PolygonLayer = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: "rgba(255,255,255,0.5)"
                }),
                stroke: new ol.style.Stroke({
                    color: "blue"
                })
            }),
            title: " polygon",
            zIndex: 10000
        });
        mapApp.olMap.addLayer(PolygonLayer);
        draw = new ol.interaction.Draw({
            source: source,
            type: type,
            title: "drawLine"
        });
        mapApp.olMap.addInteraction(draw);
        createPolygonMeasureTooltip();
        createPolygonHelpTooltip();

        var listener;
        draw.on('drawstart',
            function (evt) {
                // set sketch
                sketch = evt.feature;
                /** @type {module:ol/coordinate~Coordinate|undefined} */
                var tooltipCoord = evt.coordinate;
                listener = sketch.getGeometry().on('change', function (evt) {
                    var geom = evt.target;
                    var output;
                    output = formatArea(geom);
                    tooltipCoord = geom.getInteriorPoint().getCoordinates();

                    measurePolygonTooltipElement.innerHTML = output;
                    measurePolygonTooltip.setPosition(tooltipCoord);
                });
            }, this);

        draw.on('drawend',
            function () {
                measurePolygonTooltipElement.className = 'tooltip tooltip-static';
                measurePolygonTooltip.setOffset([0, -7]);
                // unset sketch
                sketch = null;
                // unset tooltip so that a new one can be created
                measurePolygonTooltipElement = null;
                createPolygonMeasureTooltip();
                new ol.Observable(listener);
            }, this);
    }

}

/**
 * Creates a new help tooltip
 */
function createPolygonHelpTooltip() {
    if (helpPolygonTooltipElement) {
        helpPolygonTooltipElement.parentNode.removeChild(helpPolygonTooltipElement);
    }
    helpPolygonTooltipElement = document.createElement('div');
    helpPolygonTooltipElement.className = 'tooltip hidden';
    helpPolygonTooltip = new ol.Overlay({
        element: helpPolygonTooltipElement,
        offset: [15, 0],
        positioning: 'center-left'
    });
    mapApp.olMap.addOverlay(helpPolygonTooltip);
}

/**
 * Creates a new measure tooltip
 */
function createPolygonMeasureTooltip() {
    if (measurePolygonTooltipElement) {
        measurePolygonTooltipElement.parentNode.removeChild(measurePolygonTooltipElement);
    }
    measurePolygonTooltipElement = document.createElement('div');
    measurePolygonTooltipElement.setAttribute("id", "polygon");
    measurePolygonTooltipElement.className = 'tooltip tooltip-measure';
    measurePolygonTooltip = new ol.Overlay({
        element: measurePolygonTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center',
        id: 2
    });
    mapApp.olMap.addOverlay(measurePolygonTooltip);

}

/**
 * Creates a new help tooltip
 */
function createLineHelpTooltip() {
    if (helpLineTooltipElement) {
        helpLineTooltipElement.parentNode.removeChild(helpLineTooltipElement);
    }
    helpLineTooltipElement = document.createElement('div');
    helpLineTooltipElement.className = 'tooltip hidden';
    helpLineTooltip = new ol.Overlay({
        element: helpLineTooltipElement,
        offset: [15, 0],
        positioning: 'center-left'
    });
    mapApp.olMap.addOverlay(helpLineTooltip);
}

/**
 * Creates a new measure tooltip
 */
function createLineMeasureTooltip() {
    if (measureLineTooltipElement) {
        measureLineTooltipElement.parentNode.removeChild(measureLineTooltipElement);
    }
    measureLineTooltipElement = document.createElement('div');
    measureLineTooltipElement.setAttribute("id", "line");
    measureLineTooltipElement.className = 'tooltip tooltip-measure';
    measureLineTooltip = new ol.Overlay({
        element: measureLineTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center',
        id: 1
    });
    mapApp.olMap.addOverlay(measureLineTooltip);

}

/**
 * 测量距离与面积
 * state：true启用，false关闭
 * type 为line和mian
 */
function celiangjuli(state, type) {
    if (state) {
        if (draw) {
            mapApp.olMap.removeInteraction(draw);
            addInteraction(type);
        } else {
            addInteraction(type);
        }
    } else {
        if (type === "line") {
            mapApp.olMap.removeInteraction(draw);
            mapApp.olMap.removeLayer(lineLayer)
            var overLayers = mapApp.olMap.getOverlays()
            for (var i = 0; i < overLayers.a.length; i++) {
                var lineOverLayer = overLayers.a[i]
                if (lineOverLayer.O.element.id === "line") {
                    mapApp.olMap.removeOverlay(overLayers.a[i])
                }
            }
            // mapApp.olMap.getOverlays().clear();
        } else {
            mapApp.olMap.removeInteraction(draw);
            mapApp.olMap.removeLayer(PolygonLayer)
            var overLayers = mapApp.olMap.getOverlays()
            for (var i = 0; i < overLayers.a.length; i++) {
                var polygonOverLayer = overLayers.a[i]
                if (polygonOverLayer.O.element.id === "polygon") {
                    mapApp.olMap.removeOverlay(overLayers.a[i])
                }
            }
        }

    }
}






